const Course = require('../models/Course');
const Video = require('../models/Video');

// 课程
class CourseService {
  // 创建课程
  async createCourse(title, description, price, displayImage, detailImages) {
    try {
      console.log(title, description, price, displayImage, detailImages);
      if (!Array.isArray(detailImages)) {
        detailImages = detailImages.split(','); // 将非数组值转换为单元素数组
      }
      return await Course.create({
        title,
        description,
        price,
        displayImage,
        detailImages,
      });
    } catch (error) {
      throw new Error('创建课程失败');
    }
  }

  // 获取所有课程
  async getAllCourses() {
    try {
      return await Course.findAll({
        include: {
          model: Video,
          attributes: ['id', 'title', 'url'], // 选择要返回的视频字段
        },
      });
    } catch (error) {
      throw new Error('获取所有课程失败');
    }
  }

  // 获取单个课程
  async getCourseById(id) {
    try {
      return await Course.findByPk(id, {
        include: {
          model: Video,
          attributes: ['id', 'title', 'url'], // 选择要返回的视频字段
        },
      });
    } catch (error) {
      console.log(error);
      throw new Error('获取单个课程失败');
    }
  }

  // 更新课程
  async updateCourse({ id, title, description, price }) {
    try {
      const course = await Course.findByPk(id);
      if (!course) return false;
      course.title = title;
      course.description = description;
      course.price = price;
      await course.save();
      return true;
    } catch (error) {
      throw new Error('更新课程失败');
    }
  }

  // 删除课程
  async deleteCourse(id) {
    try {
      const course = await Course.findByPk(id);
      if (!course) return false;
      await course.destroy();
      return true;
    } catch (error) {
      throw new Error('删除课程失败');
    }
  }

  // 上架课程
  async publishCourse(id) {
    try {
      const updatedCourse = await Course.update(
        { status: 'published' },
        {
          where: { id },
        }
      );

      return updatedCourse[0] > 0 ? true : false;
    } catch (error) {
      throw new Error('上架课程失败');
    }
  }

  // 下架课程
  async unpublishCourse(id) {
    try {
      const updatedCourse = await Course.update(
        { status: 'unpublished' },
        {
          where: { id },
        }
      );

      return updatedCourse[0] > 0 ? true : false;
    } catch (error) {
      throw new Error('下架课程失败');
    }
  }

  // 批量删除课程
  async deleteCourses(ids) {
    try {
      const deletedCount = await Course.destroy({
        where: {
          id: ids,
        },
      });

      return deletedCount > 0 ? true : false;
    } catch (error) {
      throw new Error('批量删除课程失败');
    }
  }
}

module.exports = new CourseService();